import os
import sys
import logging
import argparse
import pandas as pd

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# 第三方库
import matplotlib.pyplot as plt

# 设置中文显示
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False

# 本地模块
from src.data_processing.data_merging.data_merger import DataMerger
from src.config.constants import UI_SETTINGS, OUTPUT_DIR, DEBUG_DIR
from src.data_processing.data_import import DataImporter
from src.data_processing.data_preprocessing import DataPreprocessor
from src.data_processing.data_matcher import DataMatcher
from src.data_processing.result_processing import ResultProcessor
from src.config.exceptions import AppException

class HanYuePackagingTool:
    """瀚越包装工具主类，负责协调整个数据处理流程"""
    
    def __init__(self):
        """初始化汉悦包装工具"""
        # 设置日志
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler("application.log", encoding="utf-8"),
                logging.StreamHandler()
            ]
        )
        self.logger = logging.getLogger('HanYuePackagingTool')
        self.logger.info("瀚越包装工具初始化完成")
        
        # 初始化各模块
        self.data_importer = DataImporter()
        self.data_preprocessor = DataPreprocessor()
        self.data_merger = DataMerger()
        self.data_matcher = DataMatcher()
        self.result_processor = ResultProcessor()
        
        # 确保输出目录存在
        os.makedirs(OUTPUT_DIR, exist_ok=True)
        os.makedirs(DEBUG_DIR, exist_ok=True)
    
    def run(self, task_file=None, history_file=None):
        """运行完整的数据处理流程"""
        try:
            self.logger.info("开始执行数据处理流程")
            
            # 1. 数据导入
            self.logger.info("步骤1: 数据导入")
            # 从参数或用户输入获取文件路径
            if not task_file:
                task_file = input("请输入任务数据文件路径: ")
            if not history_file:
                history_file = input("请输入历史数据文件路径: ")
            
            task_data = self.data_importer.import_excel_file(task_file)
            history_data = self.data_importer.import_excel_file(history_file, is_historical=True)
            self.logger.info(f"成功导入任务数据 {len(task_data)} 条，历史数据 {len(history_data)} 条")
            
            # 2. 数据预处理
            self.logger.info("步骤2: 数据预处理")
            cleaned_task_data = self.data_preprocessor.clean_data(task_data)
            cleaned_history_data = self.data_preprocessor.clean_data(history_data)
            
            standardized_task_data = self.data_preprocessor.standardize_data(cleaned_task_data)
            standardized_history_data = self.data_preprocessor.standardize_data(cleaned_history_data)
            
            # 根据项目大纲要求：预处理后执行数据合并操作，生成待处理数据
            self.logger.info("执行预处理后的任务数据合并操作")
            merged_task_data = self.data_merger.merge_task_data(standardized_task_data, standardized_history_data)
            
            self.logger.info(f"预处理后保留任务数据 {len(merged_task_data)} 条，历史数据 {len(standardized_history_data)} 条")
            
            # 3. 数据匹配
            self.logger.info("步骤3: 数据匹配")
            # 先进行规格型号匹配
            matched_data = self.data_matcher.match_specification(
                merged_task_data, standardized_history_data
            )
            # 对匹配后的数据进行分类
            classified_data = self.data_matcher.classify_data(matched_data)
            # 执行匹配策略
            matching_results = self.data_matcher.execute_matching_strategy(classified_data)
            self.logger.info(f"匹配完成，总匹配数: {len(matching_results)}")
            
            # 4. 结果处理和导出
            self.logger.info("步骤4: 结果处理和导出")
            processed_results = self.result_processor.process_results(matching_results)
            
            # 导出结果
            output_file = os.path.join(OUTPUT_DIR, "matching_results.xlsx")
            self.result_processor.export_results(processed_results, output_file)
            self.logger.info(f"结果已导出至: {output_file}")
            self.logger.info("结果处理和导出完成")
            
            self.logger.info("数据处理流程执行完毕")
            return True
            
        except AppException as e:
            self.logger.error(f"应用程序错误: {str(e)}")
            raise
        except Exception as e:
            self.logger.error(f"未预期的错误: {str(e)}")
            raise

    def run_ui(self):
        """启动UI界面"""
        try:
            logger = logging.getLogger('HanYueUI')
            logger.info("启动瀚越包装工具UI界面")
            
            # 动态导入UI模块，避免不必要的依赖加载
            import tkinter as tk
            from src.ui.main_window import MainWindow
            
            # 启动主窗口
            app = MainWindow()
            app.run()
        except ImportError as e:
            print(f"错误: 无法导入tkinter模块 - {str(e)}")
            print("请安装tkinter: 'pip install python-tk' (Linux) 或确保Python安装包含tkinter (Windows/Mac)")
        except Exception as e:
            logging.error(f"UI启动失败: {str(e)}")
            input("按Enter键退出...")


if __name__ == "__main__":
    """主程序入口，支持命令行和UI两种模式"""
    # 创建命令行参数解析器
    parser = argparse.ArgumentParser(description='瀚越包装方案匹配工具')
    parser.add_argument('--mode', choices=['cli', 'ui'], default='ui', 
                        help='运行模式: cli(命令行)或ui(图形界面)，默认为ui')
    parser.add_argument('--task-file', type=str, help='任务数据表文件路径')
    parser.add_argument('--historical-file', type=str, help='历史包装数据文件路径')
    
    # 解析命令行参数
    args = parser.parse_args()
    
    try:
        tool = HanYuePackagingTool()
        
        # 根据模式选择运行方式
        if args.mode == 'cli':
            tool.run(task_file=args.task_file, history_file=args.historical_file)
        else:
            tool.run_ui()
            
    except Exception as e:
        logging.error(f"程序执行失败: {str(e)}")
        input("按Enter键退出...")